package com.le.tester.javaThink.fifth.chapter24_ConcurrentProgramming;

import java.time.LocalDateTime;
import java.util.function.LongSupplier;
import java.util.stream.LongStream;

/**
 * createTime：2021/8/17 14:35
 * description：时间测试,流的大小为100000000的时候，依然是没有溢出
 */
public class Summing {
    static void timeTest(String id, long checkValue, LongSupplier operation) {
        LocalDateTime startTime = LocalDateTime.now();
        long result = operation.getAsLong();
        if (result == checkValue) {
            int duration = ParallelPrime.getDuration(startTime, LocalDateTime.now());
            System.out.println("duration is " + duration + " second");
        } else {
            System.out.format("result: %d%ncheckValue: %d%n", result, checkValue);
        }
    }

    public static final int SZ = 100_000_000;

    public static final long CHECK = (long) SZ * ((long) SZ + 1) / 2;

    public static void main(String[] args) {
        //把0-100的所有数进行相加
        // long sum = LongStream.rangeClosed(0, 100).sum();
        System.out.println(CHECK);
        //没有使用并行
        timeTest("Sum Stream", CHECK, () -> LongStream.rangeClosed(0, SZ).sum());
        //使用并行
        timeTest("Sum Stream Parallel", CHECK, () -> LongStream.rangeClosed(0, SZ).parallel().sum());

        //遍历相加
        timeTest("Sum iteratored", CHECK, () -> LongStream.iterate(0, i -> i + 1).limit(SZ + 1).sum());
    }
}
